package com.yyl.render.utils

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.yyl.render.RenderConfig
import com.yyl.render.render.YYLRender
import java.io.IOException
import java.nio.ByteBuffer

object AssetsUtils {

    fun load(context: Context, name: String): String {
        val result = context.assets.open(name).reader().readText()
        val resultAll = result.replace("\\r\\n", "\n")
        RenderConfig.i("AssetsUtils", resultAll)
        return resultAll
    }

    fun loadRGBAImage(context: Context, path: String, render: YYLRender): Bitmap? {
        val inputStream = context.assets.open(path)
        val bitmap: Bitmap?
        try {
            bitmap = BitmapFactory.decodeStream(inputStream)
            if (bitmap != null) {
                val buf = ByteBuffer.allocate(bitmap.byteCount)
                bitmap.copyPixelsToBuffer(buf)
                val byteArray = buf.array()
                render.nativeUpdateFrame(
                    YYLRender.IMAGE_FORMAT_RGBA,
                    bitmap.width,
                    bitmap.height,
                    byteArray
                )
            }
        } finally {
            try {
                inputStream.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return bitmap
    }

    fun loadRGBAImage(context: Context, resId: Int, render: YYLRender): Bitmap? {
        val inputStream = context.resources.openRawResource(resId)
        val bitmap: Bitmap?
        try {
            bitmap = BitmapFactory.decodeStream(inputStream)
            if (bitmap != null) {
                val buf = ByteBuffer.allocate(bitmap.byteCount)
                bitmap.copyPixelsToBuffer(buf)
                val byteArray = buf.array()
                render.nativeUpdateFrame(
                    YYLRender.IMAGE_FORMAT_RGBA,
                    bitmap.width,
                    bitmap.height,
                    byteArray
                )
            }
        } finally {
            try {
                inputStream.close()
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        return bitmap
    }
}
